1 module global_opts;
2 
3 ///Used on targets.wasm 
4 bool serverStarted;
5 bool appleClean;
6 
7 
8 import core.thread;
9 import core.sync.semaphore;
10 import commons;
11 private Thread serverThread;
12 
13 shared ushort gameServerPort;
14 shared string gameServerHost;
15 
16 
17 private Terminal* term;
18 
19 void startServer(shared ushort* usingPort, shared string* usingHost, ref Terminal t)
20 {
21     if(serverStarted) return;
22     import server;
23     import core.stdc.stdlib;
24     serverStarted = true;
25     term = &t;
26     Semaphore s = new Semaphore();
27 	serverThread = new Thread(()
28     {
29         hipengineStartServer([], usingPort, usingHost, getHipPath("build", "wasm"), cast(shared)s);
30     }).start();
31 
32 
33     version(Windows)
34     {
35         import core.sys.windows.windef; // Windows API bindings
36         import core.sys.windows.wincon; // Windows API bindings
37 
38         static extern(Windows) BOOL handleCtrlC(DWORD ctrlType) nothrow
39         {
40             if (ctrlType == CTRL_C_EVENT) // CTRL+C signal
41             {
42                 try 
43                 {
44                     exitServer(*term);
45                     destroy(*term);
46                 }
47                 catch(Exception e){}
48                 exit(0);
49             }
50             return FALSE;
51         }
52 
53         if (!SetConsoleCtrlHandler(&handleCtrlC, TRUE))
54         {
55             throw new Exception("Failed to register CTRL+C handler.");
56         }
57 
58     }
59     else version(Posix)
60     {
61         import core.sys.posix.signal;
62         static extern(C) void handleCtrlC(int signum)
63         {
64             exitServer(*term);
65             destroy(*term);
66             exit(0);
67         }
68         alias fn = extern(C) void function(int) nothrow @nogc;
69         signal(SIGINT, cast(fn)&handleCtrlC);
70     }
71 
72     s.wait;
73 }
74 
75 void exitServer(ref Terminal t)
76 {
77     if(!serverStarted) 
78         return;
79     import std.conv: to;
80     import server;
81     t.writelnHighlighted("Shutting down the server at ", cast()gameServerHost, ":", cast()gameServerPort.to!string);
82     serverThread = null;
83     serverStarted = false;
84     stopServer();
85 }